<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\WorkOrder;
use App\Admin\Services\WorkOrderOperationLog;
use App\Admin\Services\WorkOrderService;
use App\Models\ProcessesArchive;
use App\Models\UserProcess;
use App\Models\WorkOrderComponent;
use App\Models\WorkOrderDispatch;
use App\Models\WorkOrderPic;
use App\Models\WorkOrderStopRework;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class WorkOrderController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new WorkOrder(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('workshop_id');
            $grid->column('brand_id');
            $grid->column('car_id');
            $grid->column('car_number');
            $grid->column('factory_at');
            $grid->column('user_name');
            $grid->column('user_phone');
            $grid->column('remark');
            $grid->column('is_urgent');
            $grid->column('opening_at');
            $grid->column('pre_delivery_at');
            $grid->column('maintenance_days');
            $grid->column('service_advisor_id');
            $grid->column('status');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
        
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
        
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new WorkOrder(), function (Show $show) {
            $show->field('id');
            $show->field('workshop_id');
            $show->field('brand_id');
            $show->field('car_id');
            $show->field('car_number');
            $show->field('factory_at');
            $show->field('user_name');
            $show->field('user_phone');
            $show->field('remark');
            $show->field('is_urgent');
            $show->field('opening_at');
            $show->field('pre_delivery_at');
            $show->field('maintenance_days');
            $show->field('service_advisor_id');
            $show->field('status');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new WorkOrder(), function (Form $form) {
            $form->display('id');
            $form->text('workshop_id');
            $form->text('brand_id');
            $form->text('car_id');
            $form->text('car_number');
            $form->text('factory_at');
            $form->text('user_name');
            $form->text('user_phone');
            $form->text('remark');
            $form->text('is_urgent');
            $form->text('opening_at');
            $form->text('pre_delivery_at');
            $form->text('maintenance_days');
            $form->text('service_advisor_id');
            $form->text('status');
        
            $form->display('created_at');
            $form->display('updated_at');
        });
    }

    public function getList(Request $request)
    {
        $user_workshop_id = session('workshop_id');

        $type = $request->get('type');
        $perPage = $request->input('per_page', 10);

        $query = \App\Models\WorkOrder::query();

        $today_start = date('Y-m-d 00:00:00');
        $today_end = date('Y-m-d 23:59:59');

        // 根据不同类型添加查询条件
        switch ($type) {
            case 'in_factory':
                $query->whereBetween('status', [0, 16])
                    ->where('workshop_id', $user_workshop_id);
                break;
            case 'damage_assessment':
                $query->where('');
                break;
            case 'in_production':
                $query->whereBetween('status', [1, 15])
                    ->where('workshop_id', $user_workshop_id);
                break;
            case 'pending_repair':
                $query->where('status', 0)
                    ->where('workshop_id', $user_workshop_id);
                break;
            case 'rework':
                $query->where('is_return', DEFAULT_TRUE)
                    ->whereOr('is_rework', DEFAULT_TRUE)
                    ->where('workshop_id', $user_workshop_id);
                break;
            case 'today_in':
                $query->whereBetween('created_at', [$today_start, $today_end])
                    ->where('workshop_id', $user_workshop_id);
                break;
            case 'interrupted':
                $query->where('is_stop', DEFAULT_TRUE)->where('workshop_id', $user_workshop_id);
                break;
            case 'delayed':
                $query->where('pre_delivery_at', '<' ,date('Y-m-d H:i:s'))
                    ->where('status', '<', ORDER_WAIT_PAY)
                    ->where('workshop_id', $user_workshop_id);
                break;
            case 'due_today':
                $query->whereBetween('pre_delivery_at', [$today_start, $today_end])
                    ->where('workshop_id', $user_workshop_id);
                break;
            case 'delivered_today':
                $query->whereBetween('settlement_at', [$today_start, $today_end])
                    ->where('workshop_id', $user_workshop_id);
                break;
        }

        $data = $query->paginate($perPage);

        foreach ($data->items() as $key => &$value) {
            $value->brand_title = $value->brand->title;
            $value->car_title = $value->car->title;
            $value->service_advisor_name = $value->serviceAdvisor->name;

            $dispatch = WorkOrderDispatch::where('work_order_id', $value->id)->orderBy('id', 'desc')->first();

            if ($dispatch) {
                $value->processes_archives_title = $dispatch->processes_archives_title;
                $value->dispatch_user_name = $dispatch->user_name;
            }

            if ($value->opening_at) {
                $value->opening_ats = date('Y-m-d H:i', strtotime($value->opening_at));
            }

            if ($value->pre_delivery_at) {
                $value->pre_delivery_ats = date('Y-m-d H:i', strtotime($value->pre_delivery_at));
            }

            $value->is_accident = $value->is_accident == 1 ? true : false;
            $value->is_appointment = $value->is_appointment == 1 ? true : false;
            $value->is_pre_spray = $value->is_pre_spray == 1 ? true : false;
            $value->is_return = $value->is_return == 1 ? true : false;
            $value->is_self_pay = $value->is_self_pay == 1 ? true : false;
            $value->is_urgent = $value->is_urgent == 1 ? true : false;
        }

        return response()->json([
            'data' => $data->items(),
            'total' => $data->total()
        ]);
    }

    public function export(Request $request)
    {
        $type = $request->input('type');

        $data = $this->getList($request)->getData()->data;

        $exportData = collect($data)->map(function($item) {
            return [
                '序号' => $item->index,
                '工单号' => $item->order_no,
                '车牌号' => $item->plate_no,
                '汽车品牌' => $item->brand,
                '车系' => $item->series,
                '顾问' => $item->advisor,
                '当前工序' => $item->current_process,
                '技师' => $item->technician,
                '开单时间' => $item->order_time,
                '预交时间' => $item->estimated_time
            ];
        });

        return Excel::create('车辆列表_' . date('YmdHis'), function($excel) use ($exportData) {
            $excel->sheet('Sheet1', function($sheet) use ($exportData) {
                $sheet->fromArray($exportData);
            });
        })->download('xlsx');
    }

    public function orderCreate(Request $request)
    {
        $param = $request->all();

        $param['user_id'] = Auth::guard('admin')->user()->id;
        $param['user_name'] = Auth::guard('admin')->user()->name;
        $param['workshop_id'] = Auth::guard('admin')->user()->workshop_id;

        WorkOrderService::orderCreate($param);

        return successMessage();
    }

    public function orderUpdate(Request $request)
    {
        $param = $request->all();

        WorkOrderService::orderUpdate($param);

        return successMessage();
    }

    public function orderDetail(Request $request)
    {
        $param = $request->all();

        $order = WorkOrderService::detail($param['order_id']);
        $order->car_title = $order->car->title;

        $paint_parts = WorkOrderComponent::where('work_order_id', $param['order_id'])->where('type', COMPONENT_SPRAY_PAINT)->get();

        foreach ($paint_parts as $key => &$value) {
            $value['damage_light_coefficient'] = $value['damage_coefficient'];
            $value['damage_level_type'] = damageLevelTypeTitle($value['damage_level_type']);
        }

        $order->paint_parts = $paint_parts;

        $sheet_metal_parts = WorkOrderComponent::where('work_order_id', $param['order_id'])->where('type', COMPONENT_SHEET_METAL)->get();

        foreach ($sheet_metal_parts as $key => &$value) {
            $value['damage_light_coefficient'] = $value['damage_coefficient'];
            $value['damage_level_type'] = damageLevelTypeTitle($value['damage_level_type']);
        }

        $order->sheet_metal_parts = $sheet_metal_parts;

        $order->is_accident = $order->is_accident == 1 ? true : false;
        $order->is_appointment = $order->is_appointment == 1 ? true : false;
        $order->is_pre_spray = $order->is_pre_spray == 1 ? true : false;
        $order->is_return = $order->is_return == 1 ? true : false;
        $order->is_self_pay = $order->is_self_pay == 1 ? true : false;
        $order->is_urgent = $order->is_urgent == 1 ? true : false;

        return successMessage($order);
    }

    public function assign(Request $request)
    {
        $param = $request->all();

        $processes_archive_id = $param['processes_archive_id'];
        $order_id = $param['work_order_id'];
        $technician = $param['technician'];

        $processes_archives = ProcessesArchive::where('id', $processes_archive_id)->first();

        \App\Models\WorkOrder::where('id', $order_id)->update([
            'status' => $processes_archives['sort'],
            'is_rework' => DEFAULT_FALSE
        ]);

        $operation_log_param = [
            'work_order_id' => $param['work_order_id'],
            'content' => '派工-'.$processes_archives->title,
            'type' => 1,
            'operation_id' => Auth::guard('admin')->user()->id
        ];

        //原有的派工维修类型都改为结束
        WorkOrderDispatch::where('work_order_id', $order_id)->update([
            'repair_status' => PROCESSES_AFTER,
            'actual_end_at' => date('Y-m-d H:i:s')
        ]);

        if ($param['technician']) {
            WorkOrderDispatch::create([
                'work_order_id' => $order_id,
                'processes_archives_id' => $processes_archive_id,
                'processes_archives_title' => $processes_archives->title,
                'user_id' => $technician['user_id'],
                'user_name' => $technician['user_name'],
                'repair_status' => PROCESSES_IN,
                'actual_start_at' => date('Y-m-d H:i:s')
            ]);

            $operation_log_param = array_merge($operation_log_param, [
                'user_id' => $technician['user_id'],
                'processes_archives_id' => $processes_archive_id,
            ]);
        } else {
            WorkOrderDispatch::create([
                'work_order_id' => $order_id,
                'processes_archives_id' => $processes_archive_id,
                'processes_archives_title' => $processes_archives->title,
                'repair_status' => PROCESSES_IN,
                'actual_start_at' => date('Y-m-d H:i:s')
            ]);
        }

        WorkOrderOperationLog::save($operation_log_param);

        return successMessage();
    }

    public function moveBack(Request $request)
    {
        $param = $request->all();

        $order_id = $param['work_order_id'];

        $order = \App\Models\WorkOrder::where('id', $order_id)->first();

        $processes_archives = ProcessesArchive::where('sort', $order->status)->first();

        WorkOrderDispatch::where('work_order_id', $order_id)
            ->where('processes_archives_id', $processes_archives->id)
            ->delete();

        $desc_dispatch = WorkOrderDispatch::where('work_order_id', $order_id)
            ->orderBy('id', 'desc')
            ->first();

        $desc_dispatch->repair_status = PROCESSES_IN;
        $desc_dispatch->save();

        $order->status = $order->status - 1;
        $order->save();

        $back_processes_archives = ProcessesArchive::where('sort',  $order->status)->first();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '后退工单-进入'.$back_processes_archives->title,
            'type' => 1,
            'operation_id' => Auth::guard('admin')->user()->id
        ]);

        return successMessage();
    }

    public function processesArchivesAll(Request $request)
    {
        $param = $request->all();

        $dispatch = WorkOrderDispatch::where('work_order_id', $param['work_order_id'])->get();

        if ($dispatch) {
            foreach ($dispatch as $key => $value) {
                $value->processesArchives->dispatch_id = $value->id;
                $processes_archives[] = $value->processesArchives;
            }
        }

        return successMessage($processes_archives ? array_slice($processes_archives, 0, -1) : []);
    }

    public function rework(Request $request)
    {
        $param = $request->all();

        $processes_archive_id = $param['processes_archive_id'];
        $order_id = $param['work_order_id'];
        $technician = $param['technician'];
        $rework_id = $param['rework_id'];
        $dispatch_id = $param['dispatch_id'];
        $old_dispatch_id = $param['old_dispatch_id'];

        //查询旧派工
        $old_dispatch = WorkOrderDispatch::find($old_dispatch_id);

        //创建返工记录
        WorkOrderStopRework::create([
            'work_order_id'  => $order_id,
            'processes_archives_id' => $processes_archive_id,
            'original_processes_archives_id' => $old_dispatch->processes_archives_id,
            'stop_rework_reason_id' => $rework_id,
            'order_dispatch_id' => $dispatch_id,
            'content' => $param['content'],
            'user_id' => $technician['user_id'],
            'type' => REWORK_REASON,
            'operation_id' => Auth::guard('admin')->user()->id
        ]);


//         WorkOrderDispatch::where('id', $dispatch_id)->delete();

         //查询工序
         $processes_archive = ProcessesArchive::find($processes_archive_id);

         //更改订单为内返及订单状态
         \App\Models\WorkOrder::where('id', $order_id)->update([
            'is_rework' => DEFAULT_TRUE,
            'status' => $processes_archive->sort
         ]);

         //订单内返后，新更改的工序状态修改
         WorkOrderDispatch::where('work_order_id', $order_id)
             ->where('processes_archives_id', $processes_archive_id)
             ->update([
                 'repair_status' => PROCESSES_IN
             ]);

        //旧工序删除
        $old_dispatch->delete();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '返工工单-进入'.$processes_archive->title,
            'type' => 1,
            'operation_id' => Auth::guard('admin')->user()->id
        ]);

        return successMessage();
    }

    public function stop(Request $request)
    {
        $param = $request->all();

        $order_id = $param['work_order_id'];
        $stop_id = $param['stop_id'];
        $dispatch_id = $param['dispatch_id'];

        $dispatch = WorkOrderDispatch::where('work_order_id', $order_id)
            ->where('id', $dispatch_id)
            ->first();

        //创建中断记录
        WorkOrderStopRework::create([
            'work_order_id'  => $order_id,
            'processes_archives_id' => $dispatch->processes_archives_id,
            'stop_rework_reason_id' => $stop_id,
            'order_dispatch_id' => $dispatch_id,
            'content' => $param['content'],
            'user_id' => $dispatch->user_id,
            'type' => STOP_REASON,
            'operation_id' => Auth::guard('admin')->user()->id
        ]);

        //更改中断状态
        \App\Models\WorkOrder::where('id', $order_id)->update([
            'is_stop' => DEFAULT_TRUE
        ]);

        //订单中断后，新更改的工序状态修改
        $dispatch->is_stop = DEFAULT_TRUE;
        $dispatch->save();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '中断工单-'.$dispatch->processes_archives_title,
            'type' => 1,
            'operation_id' => Auth::guard('admin')->user()->id
        ]);

        return successMessage();
    }

    public function stopContinue(Request $request)
    {
        $param = $request->all();

        $order_id = $param['work_order_id'];
        $dispatch_id = $param['dispatch_id'];

        //更改中断状态
        \App\Models\WorkOrder::where('id', $order_id)->update([
            'is_stop' => DEFAULT_FALSE
        ]);

        $dispatch =  WorkOrderDispatch::where('work_order_id', $order_id)
            ->where('id', $dispatch_id)
            ->first();

        $dispatch->is_stop = DEFAULT_FALSE;
        $dispatch->save();

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '继续工单-'.$dispatch->processes_archives_title,
            'type' => 1,
            'operation_id' => Auth::guard('admin')->user()->id
        ]);

        return successMessage();
    }

    public function settlement(Request $request)
    {
        $param = $request->all();

        $order_id = $param['work_order_id'];

        \App\Models\WorkOrder::where('id', $order_id)->update([
            'status' => ORDER_PAY,
            'settlement_at' => date('Y-m-d H:i:s')
        ]);

        WorkOrderDispatch::create([
            'work_order_id' => $order_id,
            'processes_archives_title' => '结算',
            'processes_archives_id' => 18, //固定结算ID
            'repair_status' => PROCESSES_AFTER,
            'actual_start_at' => date('Y-m-d H:i:s')
        ]);

        WorkOrderOperationLog::save([
            'work_order_id' => $order_id,
            'content' => '结算工单',
            'type' => 1,
            'operation_id' => Auth::guard('admin')->user()->id
        ]);

        return successMessage();
    }

    public function workLogAll(Request $request)
    {
        $param = $request->all();

        $dispatch = WorkOrderDispatch::where('work_order_id', $param['order_id'])->get();

        foreach ($dispatch as $key => &$value) {
            $value['repair_status_title'] = repairStatusTitle($value['repair_status']);
        }

        return successMessage($dispatch);
    }

    public function operationLogAll(Request $request)
    {
        $param = $request->all();

        $dispatch = \App\Models\WorkOrderOperationLog::where('work_order_id', $param['order_id'])->get();

        foreach ($dispatch as $key => &$value) {
            if ($value['user_id']) {
                $value['user_name'] = $value->user->name;
            }

            if ($value['processes_archives_id']) {
                $value['processes_archives_title'] = $value->processesArchives->title;
            }

            $value['operation_name'] = $value->operation->name;
        }

        return successMessage($dispatch);
    }

    public function photoLogAll(Request $request)
    {
        $param = $request->all();

        $pics = WorkOrderPic::where('work_order_id', $param['order_id'])->get();

        foreach ($pics as $key => &$value) {
            $value['created_ats'] = date("m-d H:i", strtotime($value['created_at']));
        }

        return successMessage($pics);
    }

    public function reworkStopLogAll(Request $request)
    {
        $param = $request->all();

        $stop_rework = WorkOrderStopRework::where('work_order_id', $param['order_id'])->get();

        foreach ($stop_rework as $key => &$value) {
            $value['processes_archives_title'] = $value->processesArchives->title;
            $value['stop_rework_title'] = $value->stopReworkReason->title;
            $value['type_title'] = stopReworkTitle($value->type);
        }

        return successMessage($stop_rework);
    }

    public function orderDelete(Request $request)
    {
        $param = $request->all();

        \App\Models\WorkOrder::where('id', $param['id'])->delete();

        return successMessage();
    }
}
